package com.yuanyi.controller;

import com.yuanyi.dao.TodoDao;
import com.yuanyi.entity.Todo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@RestController
public class IndexController {
    @Autowired
    TodoDao todoDao;

    public static void main(String[] args) throws IOException {
        URL url = new URL("https://api.weixin.qq.com/cgi-" +
                "bin/material/batchget_material?access_token=24_AzzX-ncXZqBGav4V3qUSa3L-" +
                "URkzIxXD57G9tg9iUp-3x-UhAPdnTMdShjAlb4qXrJP-pYRLg6ujEckdu836-"+
                "37OQUSYcEOpuHOiPkfwaoPkBi0U52JqC6gCybaXc971BfnBeztO_tnGWsgdDIUaAHAHMY");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);

        String sendStr = "{\"type\":\"voice\",\"offset\":0,\"count\":1}";

       con.getOutputStream().write(sendStr.getBytes());
       con.getOutputStream().flush();

        BufferedReader br = new BufferedReader(
                new InputStreamReader(con.getInputStream(),"utf-8")
       );

        String str;
        StringBuffer sb = new StringBuffer();
        while((str=br.readLine())!=null){
           sb.append(str);
       }

       System.out.println(sb);
    }

    @PostMapping("/index")
    public String name(HttpServletRequest req) throws IOException {
        BufferedReader br = new BufferedReader(
                new InputStreamReader(req.getInputStream(),"utf-8")
        );
        String str;
        StringBuffer sb = new StringBuffer();
        while((str=br.readLine())!=null){
            sb.append(str);
        }
      ; br.close();

        String xml = sb.toString();
        //xml ==> obj
        int start = xml.indexOf("CDATA[");
        int end = xml.indexOf("]",start);
        String toUserName = xml.substring(start+6,end);

        start = xml.indexOf("CDATA[",end);
        end = xml.indexOf("]",start);
        String fromUserName = xml.substring(start+6,end);

        Date date = new Date();
        String time = (date.getTime()/1000+"");
        //        return "<xml>\n" +
//                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
//                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
//                "  <CreateTime>"+time+"</CreateTime>\n" +
//                "  <MsgType><![CDATA[text]]></MsgType>\n" +
//                "  <Content><![CDATA[你好厉害！]]></Content>\n" +
//                "</xml>";
        String media_id = "Tm0wloeelsI3zbVLe4QVx6MKnwbYdqO4HTwNPlIXO9c";

        return "<xml>\n" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>"+time+"</CreateTime>\n" +
                "  <MsgType><![CDATA[voice]]></MsgType>\n" +
                "  <Voice>\n" +
                "    <MediaId><![CDATA["+media_id+"]]></MediaId>\n" +
                "  </Voice>\n" +
                "</xml>";
    }
    @GetMapping("/index")
    public String name(String signature,String timestamp,String nonce,String echostr){

        String[] strs = {"hehe",timestamp,nonce};
        Arrays.sort(strs);

        StringBuilder str = new StringBuilder();
        for (int i = 0;i < strs.length;i++) {
            str.append(strs[i]);
        }
        MessageDigest md = null;
        String tempStr = null;
        try
        {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.toString().getBytes());
            tempStr = byteToStr(digest);
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        if (signature.toUpperCase().equals(tempStr)) {
            return echostr;
        }

        return "";
    }
    private String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest = strDigest + byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }
    private String byteToHexStr(byte b) {
        char[] digit = {
                '0',
                '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E',
                'F' };

        char[] tempArr = new char[2];
        tempArr[0] = digit[(b >>> 4 & 0xF)];
        tempArr[1] = digit[(b & 0xF)];
        String s = new String(tempArr);
        return s;
    }


    @GetMapping(path="/add") // Map ONLY POST Requests
    public  String addNewUser (@RequestParam String name
            , @RequestParam String content) {
        Todo t = new Todo();
        t.setContent(content);
        t.setCreatedate(new Date()+"");
        t.setName(name);
        todoDao.save(t);
        return "Saved";
    }


    @GetMapping(path="/all")
    public @ResponseBody Iterable<Todo> getAllUsers() {
        return todoDao.findAll();
    }
}
